﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Xml;
using System.IO;
using p2p.Misc.Base64;

namespace p2p.File.FileManager
{
    public class FileSerialize
    {
        // the string content we need to work with
        private static string Content;
        // the object where using to save from or load into
        private static FileLayout.p2pfile p2pFile;

        // the class method to instancate when a string is given
        public FileSerialize(string content)
        {
            Content = content; 
        }

        // the class method to instancate when a string is given
        public FileSerialize(FileLayout.p2pfile p2pfile)
        {
            p2pFile = p2pfile;
        }

        //Creates an object from an XML string.
        private object FromXml(string Xml, System.Type ObjType)
        {
            // instansiate the XML Serializer object
            XmlSerializer ser = new XmlSerializer(ObjType);
            // create the string reader
            StringReader stringReader = new StringReader(Xml);
            // create an XML parser from the string reader
            XmlTextReader xmlReader = new XmlTextReader(stringReader);
            // get the object out of the XML
            object obj = ser.Deserialize(xmlReader);
            // close the readers
            xmlReader.Close();
            stringReader.Close();
            // return the object we just got
            return obj;
        }

        // Create an XML string for a given object
        private string ToXml(object Obj, System.Type ObjType)
        {
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(ObjType);
            MemoryStream ms = new MemoryStream();
            x.Serialize(ms, Obj);
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            string xml = sr.ReadToEnd();
            return xml;
        }

        public object getDycrypt()
        {
            // calls the above converter from XML to object used the data given though
            return FromXml(Content, typeof(FileLayout.p2pfile));
        }

        public string getEncrypt()
        {
            // calls the above convert to XML and passes the responce into base64 dll encoder
            return Base64.Encode(ToXml(p2pFile, typeof(FileLayout.p2pfile)));
        }
    }
}
